package th.ac.tu.engr.timemylife;

import android.database.sqlite.SQLiteDatabase;
import android.database.Cursor;
import android.provider.BaseColumns;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import android.content.ContentValues;
import android.util.Log;


public class UsageEntry {
    private static final String TAG = "UsageEntry";

    public UsageEntry() {
    }

    /* Schema of usage status table */
    public static abstract class Schema implements BaseColumns {
        public static final String TABLE_NAME = "Usage";
        public static final String COLUMN_NAME_DATE = "Date";
        public static final String COLUMN_NAME_DOW = "DayOfWeek";
        public static final String COLUMN_NAME_SYNCED = "Synced";
        public static final String COLUMN_NAME_HOUR = "Hour";
        public static final String COLUMN_NAME_HOUR0 = "Hour0";
        public static final String COLUMN_NAME_HOUR1 = "Hour1";
        public static final String COLUMN_NAME_HOUR2 = "Hour2";
        public static final String COLUMN_NAME_HOUR3 = "Hour3";
        public static final String COLUMN_NAME_HOUR4 = "Hour4";
        public static final String COLUMN_NAME_HOUR5 = "Hour5";
        public static final String COLUMN_NAME_HOUR6 = "Hour6";
        public static final String COLUMN_NAME_HOUR7 = "Hour7";
        public static final String COLUMN_NAME_HOUR8 = "Hour8";
        public static final String COLUMN_NAME_HOUR9 = "Hour9";
        public static final String COLUMN_NAME_HOUR10 = "Hour10";
        public static final String COLUMN_NAME_HOUR11 = "Hour11";
        public static final String COLUMN_NAME_HOUR12 = "Hour12";
        public static final String COLUMN_NAME_HOUR13 = "Hour13";
        public static final String COLUMN_NAME_HOUR14 = "Hour14";
        public static final String COLUMN_NAME_HOUR15 = "Hour15";
        public static final String COLUMN_NAME_HOUR16 = "Hour16";
        public static final String COLUMN_NAME_HOUR17 = "Hour17";
        public static final String COLUMN_NAME_HOUR18 = "Hour18";
        public static final String COLUMN_NAME_HOUR19 = "Hour19";
        public static final String COLUMN_NAME_HOUR20 = "Hour20";
        public static final String COLUMN_NAME_HOUR21 = "Hour21";
        public static final String COLUMN_NAME_HOUR22 = "Hour22";
        public static final String COLUMN_NAME_HOUR23 = "Hour23";
    }

    /**
     * Update or put usage data into database
     * @param now       Data timestamp
     * @param value     Number of active minutes
     */
    public static void update(Calendar now, int value) {

        Log.v(TAG, "Update method");

        SQLiteDatabase db = MyApp.getAppDb();
        int hour = now.get(Calendar.HOUR_OF_DAY);
        int date = now.get(Calendar.DAY_OF_WEEK);

        String[] projection = {
            Schema._ID,
            Schema.COLUMN_NAME_DATE,
            Schema.COLUMN_NAME_DOW,
            Schema.COLUMN_NAME_SYNCED,
            Schema.COLUMN_NAME_HOUR+hour
        };

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = formatter.format(now.getTime());

        String selection = Schema.COLUMN_NAME_DATE + " = " + dateStr;
        Cursor cursor = db.query(Schema.TABLE_NAME, projection, selection, null, null, null, null);
        ContentValues entity = new ContentValues();

        Log.v(TAG, "before IF");

        if (cursor.moveToFirst()) {

            Log.v(TAG, "cursor.moveToFirst() == true");

            entity.put(Schema.COLUMN_NAME_DATE , dateStr);
            entity.put(Schema.COLUMN_NAME_DOW , date);
            entity.put(Schema.COLUMN_NAME_HOUR+hour , value);

            //update record
            db.update(
                    Schema.TABLE_NAME,
                    entity,
                    selection,
                    new String[] { String.valueOf(Schema.COLUMN_NAME_HOUR+hour) });

            //Cursor cursor = db.query(Schema.TABLE_NAME, projection, selection, null, null, null, null);

        } else {

            // create record
            Log.v(TAG, "Create record");

            entity.put(Schema.COLUMN_NAME_DATE , dateStr);
            entity.put(Schema.COLUMN_NAME_DOW , date);
            entity.put(Schema.COLUMN_NAME_HOUR+hour , value);

            db.insert(
                    Schema.TABLE_NAME,
                    Schema.COLUMN_NAME_HOUR+hour,
                    entity);
        }

        Log.v(TAG, "Created");
    }

    /**
     * Query all unsynced records, except today
     * @param now       Data timestamp
     * @return          String of date, day of week, comma-separated integers
     */
    public static String query(Calendar now) {

        SQLiteDatabase db = MyApp.getAppDb();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = formatter.format(now.getTime());
        int hour = now.get(Calendar.HOUR_OF_DAY);

        String selection = "SELECT * FROM " + Schema.TABLE_NAME + " WHERE " +
                Schema.COLUMN_NAME_SYNCED + " = 0 AND " +
                Schema.COLUMN_NAME_DATE + " = " + dateStr +
                "ORDER BY" + Schema._ID +"DESC";

        Cursor cursor = db.rawQuery(selection, null);
        ContentValues entity = new ContentValues();

        String reply = "";
        if (cursor.moveToFirst()) {
           // do {
                // Concatenate string

                for(int i = 0 ; i < 24 ; i++) {

                    int itemId = cursor.getInt(
                            cursor.getColumnIndexOrThrow(Schema.COLUMN_NAME_HOUR + hour)
                    );
                    if (i == 23)
                        reply = reply + itemId ;
                    else
                        reply = reply + itemId + ",";
                }

           // } while(cursor.moveToNext());

            Log.v(TAG, "Query = "+reply);



        }
        entity.put(Schema.COLUMN_NAME_SYNCED , 1);
        db.update(
                Schema.TABLE_NAME,
                entity,
                selection,
                new String[] { String.valueOf(Schema.COLUMN_NAME_SYNCED) });

        Log.v(TAG, "Set Synced = 1");


        return reply;
    }

    public static void addDate(Calendar now) {

        int date = now.get(Calendar.DAY_OF_WEEK);

        SQLiteDatabase db = MyApp.getAppDb();
        ContentValues values = new ContentValues();

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = formatter.format(now.getTime());

        values.put(Schema.COLUMN_NAME_DATE, dateStr);
        values.put(Schema.COLUMN_NAME_DOW, date);

        db.insert(
                Schema.TABLE_NAME,
                null,
                values);


    }
}